import Taro, { Component, Config } from '@tarojs/taro'
import { Button, Image, ScrollView, Text, View } from '@tarojs/components'
import './index.scss'
import classNames from 'classnames'
import { USER_INFO } from '@/config/storage'
import headImg from '@/assets/icon/user-avatar.png'
import { getAppConfig, verifyUserLogin, getRandomPageNumber, getBrand } from '@/utils/storage'
import { getUserInfo, getMyCouponPage } from "@/api/userApi"
import { OSS, TAB_BAR_HEIGHT, USER_DISTRIBUTION, USER_ORDER_MENU, USER_SERVICE_MENU } from '@/config/config'
import { toAnyPage, toOrderListPage, toUserLoginPage, toHomePage, tobindingmobile } from '@/utils/page_router'
import { CustomerService, TabBar, Version, GoodsFiveList, TitleOne, LoadMore, FyImg } from '@/components/index'
import { getCount, getPage } from "@/api/productApi";
import { getCustomPage } from "@/api/pageApi";
import GoodsCategories from "@/components/custom-layout/goods-categories"
import CarouselTwo from "@/components/custom-layout/carousel-two"
import GoodsTwo from "@/components/custom-layout/goods-two";
import UserGg from '@/assets/images/user-bg.png'
import styles from './index.module.scss'
import UserBuyRecordTwo from "@/components/user-buy-record/record-two";
import QrCodeModal from "./qrCode-modal/index";

const info = Taro.getStorageSync(USER_INFO)
const scroll: any = {}
const fun = function () { }
export default class Index extends Component {
  state: any
  config: Config = {
    backgroundColor: process.env.backgroundColor,
    enablePullDownRefresh: true,
    navigationBarTextStyle: process.env.navigationBarTextStyle,
    navigationBarBackgroundColor: process.env.backgroundColor
  }

  constructor(props) {
    super(props)

    this.state = {
      isLogin: false,
      userInfo: Taro.getStorageSync(USER_INFO) || {},
      orderMenu: getAppConfig(USER_ORDER_MENU) || [],
      otherMenu: getAppConfig(USER_SERVICE_MENU) || [],
      isDistribution: Number(getAppConfig(USER_DISTRIBUTION)),
      categoryList: {},
      visible: false
    }
  }

  componentDidShow() {
    verifyUserLogin({
      success: () => {
        this.setState({
          isLogin: true
        })
        this.getUserData().then()
        this.getGoodsPage()
      },
      fail: () => {
        this.setState({
          isLogin: false,
          userInfo: {}
        }, () => {
          Taro.stopPullDownRefresh()
        })
      }
    })
    // this.getGoodsPage()
  }

  // 公众号弹窗
  qrCodeModel(event) {
    event.stopPropagation()
    this.setState({
      visible: true
    })
  }
  changeVisible(bool) {
    this.setState({
      visible: bool
    })
  }

  //  分页获取推荐商品
  getGoodsPage() {
    getCustomPage('goods_commend').then(({ data }) => {
      const Index = data.content.findIndex(item => item.key === 'goodsCategories')
      const carousel = data.content.findIndex(item => item.key === 'carousel')
      if (Index >= 0) {
        this.setState({
          categoryList: data.content[Index],
          carousel: data.content[carousel]
        })
      }
    })
    // const config = getAppConfig('productRandom')
    // getCount().then(res => {
    //   getPage({ page: config === '1' ? getRandomPageNumber() : 1, limit: 6 }).then(({ data }) => {
    //     this.setState({
    //       // @ts-ignore
    //       goodsList: data.list
    //     })
    //   })
    // })
  }
  //  监听用户下拉刷新事件。
  onPullDownRefresh() {
    this.getUserData().then()
  }

  //  获取用户信息
  async getUserData() {
    const couponData = await getMyCouponPage({ page: 1, limit: 1 }).then(({ data }) => data)
    getUserInfo().then(({ data }) => {
      Taro.setStorageSync(USER_INFO, data)
      this.setState({
        userInfo: Object.assign({ couponNumber: couponData.totalCount }, data),
      }, () => {
        Taro.stopPullDownRefresh()
      })
    }).catch(() => {
      this.setState({
        isLogin: false,
        userInfo: {}
      }, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  onPageScroll(res: any) {
    scroll.onPageScroll && scroll.onPageScroll(res.scrollTop)
  }

  onReachBottom() {
    scroll.onReachBottom && scroll.onReachBottom()
  }

  tobingphone() {
    tobindingmobile()
  }

  render() {
    const { isLogin, userInfo, orderMenu, otherMenu, categoryList, carousel, visible } = this.state
    return (
      // @ts-ignore
      <View className='user-page xf-page'>
        {/*<View className='xf-page-fixed-bg' style={{ backgroundImage: `url(${OSS}/system/image/shop_list_bg.png)` }}/>*/}
        <View className='xf-page-fixed-bg' style={{ backgroundImage: `url(${UserGg})` }} />
        <View className='page-scroll'>
          {/*<View className='user-info f-g-4' onClick={userInfo.telephone ? fun : () => toUserLoginPage()}>*/}
          <View className='user-info f-g-4'>
            <View className='user-info-cont'>
              <Text>
                <Image src={userInfo.headImg || headImg} className='user-info__avatar' />
                <View className="phone" onClick={this.tobingphone.bind(this)}>绑定手机</View>
              </Text>
              {
                isLogin ? (
                  <View className='user-info__box d-f f-d-c'>
                    <View className='user-info__bottom f-g-4'>
                      <View className='user-info__code t-o-e'>{userInfo.id}</View>
                    </View>
                  </View>
                ) : (
                  <View className='user-info__box'>
                    <View className='user-info__name'>未登录</View>
                  </View>
                )
              }
            </View>
            <View className='user-info-qrCode' onClick={this.qrCodeModel.bind(this)}>
              <View>关注有礼</View>
              <FyImg className='publicQrCode' src={getAppConfig('publicQrCode')} />
            </View>
          </View>

          {/*<View className='member-box d-f a-i-c j-c-b' onClick={() => toMemberOpenPage()}>*/}
          {/*  <View className='member-crown d-f a-i-c bnn-icon'>*/}
          {/*    <View className='member-crown__icon'>&#xe60e;</View>*/}
          {/*    <View className='member-crown__text'>{userInfo.isVip ? userInfo.vipName : '黑金会员'}</View>*/}
          {/*  </View>*/}
          {/*  <Text className='member-right bnn-icon'>{userInfo.isVip ? '查看详情' : '立即开通'}&#xe866;</Text>*/}
          {/*</View>*/}

          {/*<View className='user-card'>*/}
          {/*  <View className='total-list bnn-number'>*/}
          {/*    <View className='total-item thin-border__r' onClick={() => toWalletPage()}>*/}
          {/*      <Text className='total-name'>我的余额</Text>*/}
          {/*      <Text className='total-amount'>{formatNumber(userInfo.amount)}</Text>*/}
          {/*    </View>*/}
          {/*    <View className='total-item thin-border__r' onClick={() => toIntegralPage()}>*/}
          {/*      <Text className='total-name'>当前积分</Text>*/}
          {/*      <Text className='total-amount'>{formatNumber(userInfo.totalScore)}</Text>*/}
          {/*    </View>*/}
          {/*    <View className='total-item' onClick={() => toCouponPage()}>*/}
          {/*      <Text className='total-name'>优惠券</Text>*/}
          {/*      <Text className='total-amount'>{formatNumber(userInfo.couponNumber)}</Text>*/}
          {/*    </View>*/}
          {/*  </View>*/}
          {/*</View>*/}

          <View className='user-card'>
            <View className='user-card__head' onClick={() => toOrderListPage()}>
              <Text className='user-card__title'>我的订单</Text>
              <Text className='user-card__more bnn-icon'>全部订单&#xe866;</Text>
            </View>
            <View className='user-card__body'>
              <View className='thin-border__b' />
              {/*// @ts-ignore*/}
              <ScrollView enhanced scrollX show-scrollbar={false} className='order-type'>
                <View className='order-type__list'>
                  {
                    orderMenu.map((i, k) => {
                      return (
                        <View key={k} className='order-type__item' onClick={() => toAnyPage(i.url)}>
                          <Image src={i.src} className='order-type__icon' />
                          <View className='order-type__name'>{i.title}</View>
                        </View>
                      )
                    })
                  }
                </View>
              </ScrollView>
              {/*{isLogin && !userInfo.telephone && <View className='bind-phone'>*/}
              {/*  <View className='bind-phone__box d-f a-i-c j-c-b'>*/}
              {/*    <Text className='bind-phone__text'>绑定手机有助于我们为您提供更优质的服务</Text>*/}
              {/*    <Button openType='getPhoneNumber' className='bind-phone__btn xf-btn xf-btn-primary xf-btn-round' onClick={() => toUserLoginPage()}>立即绑定</Button>*/}
              {/*  </View>*/}
              {/*</View>}*/}
            </View>
          </View>
          <View className={classNames(styles.signBox, 'user-card')} onClick={() => toHomePage()}>
            <FyImg src={getAppConfig('userSignImg')} className={styles.signImg} />
            <View className={styles.signText}>我的{getBrand()}{info.totalScore}</View>
          </View>

          {!!otherMenu.length && <View className='user-card'>
            {/*<View className='user-card__head'>*/}
            {/*  <Text className='user-card__title'>更多服务</Text>*/}
            {/*</View>*/}
            <View className='operate-list'>
              {
                otherMenu.map((i, k) => {
                  return (
                    <View key={k} className='operate-item' onClick={() => toAnyPage(i.url)}>
                      <Image src={i.src} className='operate-icon' />
                      <View className='operate-name'>{i.title}</View>
                    </View>
                  )
                })
              }
            </View>
          </View>}
        </View>

        {carousel && <View style={{ marginBottom: '20px' }}>
          <CarouselTwo {...carousel} />
        </View>}
        {categoryList.list && <GoodsCategories {...categoryList} scroll={scroll} />}
        {/*<View id='goods-hot' className='goods-card user-card'>*/}
        {/*  <View className='goods-card__head'>*/}
        {/*    <TitleOne>更多美好生活</TitleOne>*/}
        {/*  </View>*/}
        {/*  /!*<GoodsOneList list={goodsList}/>*!/*/}
        {/*  <GoodsFiveList list={goodsList}/>*/}
        {/*</View>*/}

        <CustomerService isOpened />

        <QrCodeModal show={visible} onChange={this.changeVisible.bind(this)} />

        <Version />
        {/*{!isLogin && <View className='verify-login' onClick={() => toUserLoginPage()}/>}*/}
        <View style={{ height: `${TAB_BAR_HEIGHT}px` }} />
        <TabBar />
      </View>
    )
  }
}
